package com.lizemin.custom.classloader.controller;

import com.lizemin.custom.classloader.classloader.FileSystemClassloader;
import com.lizemin.custom.classloader.encrypt.Encryptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lzm
 * @date 2025/6/2 14:20
 * @description
 */
@RestController
public class UserController {

    @Value("${encrypt.algorithm}")
    private String algorithm;

    /**
     *不使用自定义类加载器
     *
     * @param plaintext  待加密的明文
     * @return   加密后的密文
     */
    @PostMapping ("/encrypt")
    @SuppressWarnings("unchecked")
    public String encrypt(@RequestBody String plaintext) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        // 通过反射创建加密算法的实例对象
        Class<Encryptor> clazz = (Class<Encryptor>) Class.forName(algorithm);
        Encryptor encryptor = clazz.newInstance();
        return encryptor.encrypt(plaintext);
    }

    /**
     * 使用自定义类加载器
     *
     * @param plaintext  待加密的明文
     * @return   加密后的密文
     */
    @PostMapping ("/encryptWitchCustomClassloader")
    @SuppressWarnings("unchecked")
    public String encryptWitchCustomClassloader(@RequestBody String plaintext) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        // 通过每次创建一个新的自定义类加载器来实现热加载
        FileSystemClassloader classloader = new FileSystemClassloader("C:\\Users\\15871\\Documents\\csdn\\classloader");
        // 使用自定义类加载器加载项目之外的类
        Class<Encryptor> clazz = (Class<Encryptor>) Class.forName(algorithm, false, classloader);
        Encryptor encryptor = clazz.newInstance();
        return encryptor.encrypt(plaintext);
    }

}
